<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:58
 */

namespace app\admin\service\business\controllers\Ad\Ad\Models;


use app\admin\service\model\BaseModel;
use app\model\Ad;

class AdModel extends BaseModel
{
    /**
     * 获取列表
     *
     * @param array $where
     * @param array $field
     * @param bool $isPage
     * @param int $page
     * @return mixed
     */
    public function getList(array $where, array $field = [], bool $isPage = true, int $page = 10)
    {
        $this -> page = $page;
        $this -> isPage = $isPage;

        $query = Ad::field($field ?: ['id', 'name', 'cate_id', 'resource', 'sort', 'status', 'target', 'create_time', 'update_time']) -> with(['cate' => function ($query){
            $query -> field(['id', 'name']);
        }]);

        if($where) {
            // 标题筛选
            if(isField($where, 'name')) {
                $query -> whereLike('name', "%{$where['name']}%");
            };

            // 时间筛选
            if(isField($where, 'start') && isField($where, 'end')) {
                $query -> whereBetweenTime('create_time', $where['start'], $where['end']);
            }

            // 广告分类筛选
            if(isField($where, 'cate_id')) {
                $query -> where('cate_id', $where['cate_id']);
            }

            // 状态筛选
            if(isField($where, 'status')) {
                $query -> where('status', $where['status']);
            }
        }

        return $this -> all($query);
    }

    /**
     * 获取单条
     *
     * @param int $id
     * @param array $field
     * @return mixed
     */
    public function getFind(int $id, array $field = [])
    {
        $query = Ad::where('id', $id)
                -> field($field ?: ['id', 'name', 'link', 'cate_id', 'resource', 'description']);

        return $this -> one($query);
    }

    /**
     * 添加
     *
     * @param array $data
     * @return mixed
     */
    public function insert(array $data)
    {
        return $this -> add(Ad::class, $data);
    }

    /**
     * 修改
     *
     * @param array $data
     * @param int $id
     * @return mixed
     */
    public function edit(array $data, int $id)
    {
        return $this -> update(Ad::class, array_merge($data, [
            'id' => $id
        ]));
    }

    /**
     * 删除
     *
     * @param int $id
     * @return mixed
     */
    public function delete(int $id)
    {
        return $this -> del(Ad::class, [ $id ]);
    }

    /**
     * 标题是否在同一分类下重复
     *
     * @param string $name
     * @param string $cateId
     * @param int $id
     * @return mixed
     */
    public function isUnique(string $name, string $cateId, int $id){
        $query = Ad::where('id', '<>', $id)
                -> where('name', $name)
                -> where('cate_id', $cateId);

        return $this -> value($query, 'id');
    }
}
